#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define PATH "."
#define FILENAME "fifo"
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    }while(0)

using namespace std;

class NameFifo
{
public:
    NameFifo(const string &path, const string &name)
        :_path(path), _name(name)
    {
        _fifoname = _path + "/" + _name;
        umask(0);
        int n = mkfifo(_fifoname.c_str(), 0666);
        if(n != 0)
        {
            ERR_EXIT("mkfifo");
        }
        else 
        {
            cout << "mkfifo success" << endl;
        }
    }

    ~NameFifo()
    {
        int n = unlink(_fifoname.c_str());
        if(n == 0)
        {
            cout << "removefifo success" << endl;
        }
        else
        {
            ERR_EXIT("unlink");
        }
    }
private:
    string _path;
    string _name;
    string _fifoname;
};

class FileOper
{
public:
    FileOper(const string &path, const string &name)
        :_path(path), _name(name)
    { _fifoname = _path + "/" + _name; }

    void OpenForRead()
    {
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open_file");
        }
        else 
        {
            cout << "open success" << endl;
        }
    }

    void OpenForWrite()
    {
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if(_fd < 0)
        {
            cerr << "open error" << endl;
            exit(1);
        }
        else 
        {
            cout << "open success" << endl;
        }
    }

    void Read()
    {
        char buff[1024];
        while(true)
        {
            int n = read(_fd, buff, sizeof(buff)-1);
            if(n > 0)
            {
                buff[n] = 0;
                cout << "client say:" << buff << endl;
            }
            else if(n == 0)
            {
                cout << "client quit " << n << endl;
                break;
            }
            else 
            {
                cerr << "read error" << endl;
                break;
            }
        }
    }

    void Wirte()
    {
        string mess;
        while(true)
        {
            cout << "please enter: ";
            cin >> mess;
            int n = write(_fd, mess.c_str(), mess.size());
            if(n > 0)
            {
                cout << "send success" << endl;
            }
            else
            {
                cout << "send failed" << endl;
            }
        }
    }

    ~FileOper()
    {
        if(_fd > 0)
            close(_fd);
    }
private:
    string _path;
    string _name;
    string _fifoname;
    int _fd;
};